package org.example;/*
 * title:
 * author:
 * date:
 * description:
 * */

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DeadlockSimulator {
    public static void main(String[] args) {
        final Lock sharedLock = new ReentrantLock(); // 共享锁

        // 主线程启动子线程
        Thread subThread = new Thread(() -> {
            System.out.println("Sub-thread starts.");

            // 子线程创建并启动孙子线程，孙子线程尝试获取锁
            Thread grandChildThread = new Thread(() -> {
                System.out.println("GrandChild-thread starts.");

                sharedLock.lock(); // 尝试获取锁

                try {
                    System.out.println("GrandChild-thread got the lock.");

                    // 此处模拟长时间运行或调试暂停的情况
                    Thread.sleep(10000); // 长时间暂停，模拟断点效果
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    sharedLock.unlock(); // 释放锁
                    System.out.println("GrandChild-thread released the lock.");
                }
            }, "GrandChildThread");
            grandChildThread.start();

            try {
                grandChildThread.join(); // 等待孙子线程结束
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }

            System.out.println("Sub-thread ends.");
        }, "SubThread");
        subThread.start();

        // 主线程尝试获取相同的锁，但可能因孙子线程持有而阻塞
        try {
            sharedLock.lock();
            System.out.println("Main thread got the lock.");
            sharedLock.unlock(); // 立即释放，仅做演示
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Main thread naturally ends.");
    }
}
